package org.lmind.osgi.bundle.manager.internal;

import java.io.File;
import java.util.ArrayList;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleBundleLoader {
	
	private static Logger logger = LoggerFactory.getLogger(SimpleBundleLoader.class);
	
	public static final String BUNDLES_PATH = "bundles";
	
	private BundleContext context;

	public BundleContext getContext() {
		return context;
	}

	public void setContext(BundleContext context) {
		this.context = context;
	}


	public void loadAll() {
		
		File path = new File(BUNDLES_PATH);
		ArrayList<Bundle> bundles = new ArrayList<Bundle>();
		loadBundles(path, bundles);
//		for (File bundlePath : path.listFiles()) {
//			if (!bundlePath.isFile())
//				continue;
//			String location = "file:///" + bundlePath.getAbsolutePath();
//			try {
//				Bundle bundle = context.installBundle(location);
//				bundles.add(bundle);
//				logger.info("装载bundle成功:" + bundle.getSymbolicName() + ",location=" + location);
//			} catch (BundleException e) {
//				logger.warn("装载bundle失败;location=" + location, e);
//			}
//		}
		
		for (Bundle bundle : bundles) {
			try {
				bundle.start();
				logger.warn("启动bundle成功:" + bundle.getSymbolicName());
			} catch (BundleException e) {
				logger.warn("启动bundle失败:" + bundle.getSymbolicName(), e);
			}
		}
		
	}
	
	private void loadBundles(File path, ArrayList<Bundle> bundles) {
		for (File file : path.listFiles()) {
			if (file.isFile()) {
				String location = "file:///" + file.getAbsolutePath();
				try {
					Bundle bundle = context.installBundle(location);
					bundles.add(bundle);
					logger.info("装载bundle成功:" + bundle.getSymbolicName() + ",location=" + location);
				} catch (BundleException e) {
					logger.warn("装载bundle失败;location=" + location, e);
				}
			} else if (file.isDirectory()) {
				loadBundles(file, bundles);
			}
		}
	}

}
